#include "Timer6.h"

void TIM6_Config(uint16_t Period, uint16_t Prescaler)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6,  ENABLE);	//TIM6挂载在APB1总线上
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOF, ENABLE);	//开启GPIOF
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,  ENABLE);	//开启复用时钟
	
	TIM_TimeBaseInitTypeDef TIM_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	EXTI_InitTypeDef EXTI_InitStructure;
	GPIO_InitTypeDef GPIO_InitStructure;
	
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOF, GPIO_PinSource5);	//PF5
	
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_Out_PP;	//推挽输出
	GPIO_InitStructure.GPIO_Pin   = EXTI_PIN5;			//检测输入的引脚，外部中断引脚
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
	GPIO_Init(EXTI_PROT, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_IPU;	//进行下降沿捕获 取相反的状态
	GPIO_InitStructure.GPIO_Pin   = EXTI_CHFA;		//检测输入的引脚，连接点
	GPIO_Init(EXTI_PROT, &GPIO_InitStructure);
	
	EXTI_InitStructure.EXTI_Line = EXTI_Line5;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;		//中断触发
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;	//上升沿触发
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);							//外部中断初始化
	
	TIM_InitStructure.TIM_Period = Period;
	TIM_InitStructure.TIM_Prescaler = Prescaler;
	TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;	//基本定时器只支持向上计数
	TIM_InitStructure.TIM_RepetitionCounter = DISABLE;		//重复计数次数，基本定时器也不支持
	TIM_TimeBaseInit(TIM6, &TIM_InitStructure);
	
	TIM_ClearITPendingBit (TIM6, TIM_IT_Update);				//先清除中断标志位
	TIM_ITConfig(TIM6, TIM_IT_Update | TIM_IT_Trigger, ENABLE);	//使能
	TIM_Cmd(TIM6, ENABLE);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
	NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn ;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	
	NVIC_InitStructure.NVIC_IRQChannel = TIM6_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	
}

void TIM6_IRQHandler(void)//500ms基准定时
{
	if (TIM_GetITStatus (TIM6, TIM_IT_Update) == SET )
	{
		GPIO_WriteBit ( EXTI_PROT, EXTI_CHFA, (BitAction)(!GPIO_ReadOutputDataBit(EXTI_PROT, EXTI_CHFA)) );	//PF4取反
		TIM_ClearITPendingBit (TIM6, TIM_IT_Update);	//清除中断标志位
	}
}

void EXTI9_5_IRQHandler(void)
{
	if (EXTI_GetITStatus(EXTI_Line5) != RESET)//获取中断状态 ，这个引脚 != 0, 就是产生中断了
	{
//		GPIO_WriteBit ( LED0_PORT, LED0, (BitAction)(!GPIO_ReadOutputDataBit(LED0_PORT, LED0)) );	//PB5取反
		
		GPIO_ResetBits(LED0_PORT, GPIO_Pin_5);
		
		EXTI_ClearITPendingBit(EXTI_Line5);
	}
}


